<?php

declare(strict_types=1);

namespace app\model;

use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use think\Model;

/**
 * @mixin \think\Model
 */
class MessageCode extends Model
{
  //

  protected static $typeHandler = [
    'register_email' => [
      'title' => '邮箱注册验证',
      'type' => 'email'
    ],
    'rebind_email' => [
      'title' => '绑定新验证',
      'type' => 'email'
    ],
    'forget_email' => [
      'title' => '忘记密码',
      'type' => 'email'
    ],
  ];


  public static  function verify(string $account, string $code, string $type)
  {

    $model_code  = MessageCode::where('account', $account)
      ->where('code', $code)
      ->where('type', $type)
      ->where('status', 0)
      ->find();

    if (empty($model_code)) {
      return false;
    }

    // TODO:验证过期

    $model_code->status = 1;
    $model_code->save();
    return true;
  }

  public static function build(string $account, string $type): MessageCode
  {

    // TODO:进行安全验证
    $code = mt_rand(100000, 999999);

    $data = [
      'code' => $code,
      'account' => $account,
      'type' => $type,
    ];

    $model_code = MessageCode::create($data);

    return $model_code;
  }

  public static function buildAndSend(string $account, string $type)
  {
    $message = self::build($account, $type);
    return self::send($message);
  }

  public static function send(MessageCode $message)
  {
    switch (self::$typeHandler[$message->getData('type')]['type']) {
      case 'email':
        $result = self::sendByEmail($message);
        break;

      default:
        # code...
        break;
    }

    return $result;
  }

  public static function sendByEmail(MessageCode $message)
  {
    $message_content = get_system_config('email_message_tpl');

    $message_content = str_replace('%site_title%', get_system_config('site_name'), $message_content);
    $message_content = str_replace('%email%', $message->account, $message_content);
    $message_content = str_replace('%code%', $message->code, $message_content);


    $transport = (new Swift_SmtpTransport(get_system_config('email_smtp_host'), get_system_config('email_smtp_port')))
      ->setUsername(get_system_config('email_smtp_account'))
      ->setPassword(get_system_config('email_smtp_password'));

    $mailer = new Swift_Mailer($transport);

    $email_message = (new Swift_Message(get_system_config('site_name') . '邮箱验证'))
      ->setFrom(get_system_config('email_smtp_account'))
      ->setTo([
        $message->account
      ])
      ->setBody($message_content);

    $mailer->send($email_message);

    return true;
  }
}
